package com.scorekeeper.objects;

import java.util.Date;

import com.scorekeeper.utils.DBProvider;
import com.scorekeeper.utils.Loader;

import android.os.Parcel;
import android.os.Parcelable;

public class Game implements Parcelable {
	public int _id;
	public Date gameDate;
	public int homeTeamId;
	public int awayTeamId;
	public int homeScore;
	public int awayScore;
	public int seasonId;
	
	public Game() {
		this._id = -1;
		this.homeTeamId = 0;
		this.awayTeamId = 0;
		this.seasonId = 0;
	}
	
	public Season season() {
		if (seasonId != 0) {
			return (new Loader()).loadSeason(seasonId);
		}
		
		return null;
	}
	
	public Team homeTeam() {
		if (homeTeamId != 0) {
			return (new Loader()).loadTeam(homeTeamId);
		}
		
		return null;
	}
	
	public Team awayTeam() {
		if (awayTeamId != 0) {
			return (new Loader()).loadTeam(awayTeamId);
		}
		
		return null;
	}
	
	public int describeContents() { return hashCode(); }
	
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(this._id);
		dest.writeValue(this.gameDate);
		dest.writeInt(this.homeTeam()._id);
		dest.writeInt(this.awayTeam()._id);
	}
	
	public void loadFromParcel(Parcel loadFrom) {
		this._id = loadFrom.readInt();
		this.gameDate = (Date) loadFrom.readValue(Date.class.getClassLoader());
		this.homeTeamId = loadFrom.readInt();
		this.awayTeamId = loadFrom.readInt();
		this.homeScore = loadFrom.readInt();
		this.awayScore = loadFrom.readInt();
	}
	
	public void save() {
		DBProvider db = new DBProvider();
		
		if (this._id != -1) {
			//update
			db.updateObject(DBProvider.Table.GAME, this);
		} else {
			//insert
			db.saveObject(DBProvider.Table.GAME, this);
		}
	}
}